<template>
  <div class="countdown">
    <span class="block">{{ days || 0 }}</span>
    <span class="text">天</span>
    <span class="block">{{ hours || 0 }}</span>
    <span class="text">时</span>
    <span class="block">{{ minutes || 0 }}</span>
    <span class="text">分</span>
    <span class="block">{{ seconds || 0 }}</span>
    <span class="text">秒</span>
  </div>
</template>

<script>
export default {
  props: {
    endTime: {
      type: String,
      default: "",
      required: true,
    },
  },
  data() {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      intervalId: null,
    };
  },
  watch: {
    endTime(newTime) {
      this.updateCountdown(newTime);
    },
  },
  mounted() {
    this.updateCountdown(this.endTime);
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  },
  methods: {
    updateCountdown(endTimeString) {
      const endTime = new Date(endTimeString).getTime();
      clearInterval(this.intervalId);
      this.intervalId = setInterval(() => {
        const now = new Date().getTime();
        const distance = endTime - now;
        if (distance <= 0) {
          clearInterval(this.intervalId);
          this.days = this.hours = this.minutes = this.seconds = 0;
          this.$emit("countdown-end");
        } else {
          this.days = this.padZero(Math.floor(distance / (1000 * 60 * 60 * 24)));
          this.hours = this.padZero(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
          this.minutes = this.padZero(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)));
          this.seconds = this.padZero(Math.floor((distance % (1000 * 60)) / 1000));
          
        }
      }, 1000);
    },
    // 添加一个辅助方法来格式化数字
padZero(num) {
  return num < 10 ? '0' + num : num.toString();
}
  },
};
</script>

<style scoped>
.countdown {
  display: inline;

  gap: 5px;
}
.countdown .block {
  font-weight: bold;
  font-size: 30px;
  color: #4c4c4c;
  margin:0 10px;
}
.countdown .text {
  font-size: 16px;
  color: #4c4c4c;
}
</style>
